<template>
  <div class="page-group-activity">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form
        ref="test-form"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            :label="$t('product.prodName') + ':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.prodName"
              :placeholder="$t('product.prodName')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('groups.eventName') + ':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.activityName"
              :placeholder="$t('groups.eventName')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('group.actStatus') + ':'"
            class="search-form-item"
          >
            <el-select
              v-model="searchForm.status"
              :placeholder="$t('group.actStatus')"
              @change="handleStatusChange"
            >
              <el-option
                :label="$t('group.startUsing')"
                :value="1"
              />
              <el-option
                :label="$t('groups.expired')"
                :value="0"
              />
              <el-option
                :label="$t('groups.notEnabled')"
                :value="2"
              />
              <el-option
                :label="$t('groups.over')"
                :value="5"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('group.search') }}
            </div>
            <div
              class="default-btn"
              @click="clearSearch"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 搜索栏end -->
    <!-- 表格主体 -->
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('group:activity:save')"
          class="default-btn primary-btn"
          @click="onAddOrUpdate()"
        >
          {{ $t('groups.newJoinGroupActivity') }}
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-con prod-table">
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
        >
          <el-table-column
            fixed
            prop="activityName"
            :label="$t('groups.eventName')"
            min-width="240"
          >
            <template #default="scope">
              <div>
                <span class="table-cell-text line-clamp-one">{{ scope.row.activityName }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            align="left"
            prop="prodName"
            :label="$t('product.prodInfo')"
            min-width="200"
          >
            <template #default="scope">
              <div class="table-cell-con">
                <div class="table-cell-image">
                  <ImgShow :src="scope.row.pic" />
                </div>
                <span class="table-cell-text">{{ scope.row.prodName }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="groupNumber"
            :label="$t('group.groupType')"
            min-width="150"
          >
            <template #default="scope">
              <div>{{ scope.row.groupNumber }}{{ $t('groups.groupOfPeople') }}</div>
            </template>
          </el-table-column>

          <el-table-column
            prop="startTime"
            :label="$t('group.actStartTime')"
            min-width="230"
          />

          <el-table-column
            prop="endTime"
            :label="$t('group.actEndTime')"
            min-width="230"
          />

          <el-table-column
            prop="groupOrderCount"
            :label="$t('group.groupOrderCount')"
            min-width="230"
            sortable
          />

          <el-table-column
            prop="status"
            :label="$t('group.actStatus')"
            min-width="150"
          >
            <template #default="scope">
              <div class="tag-text">
                {{
                  [
                    $t('groups.expired'),
                    $t('group.startUsing'),
                    $t('groups.notEnabled'),
                    $t('groups.offlineViolation'),
                    $t('groups.moderated'),
                    $t('groups.over')
                  ][scope.row.status]
                }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            align="center"
            :label="$t('crud.menu')"
            min-width="280"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="scope.row.status === 2"
                  class="default-btn text-btn"
                  @click="activeGroupActivity(scope.row.groupActivityId)"
                >
                  {{ $t('groups.startUsing') }}
                </div>

                <div
                  v-if="isAuth('group:activity:update')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.groupActivityId)"
                >
                  {{
                    scope.row.status === 5 || scope.row.status === 0
                      ? $t('live.view')
                      : $t('groups.editEvent')
                  }}
                </div>
                <div
                  v-if="scope.row.status === 1"
                  class="default-btn text-btn"
                  @click="invalidActivityHandle(scope.row)"
                >
                  {{ $t('groups.invalidActivity') }}
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="$t('groups.failureTip')"
                    placement="right"
                  >
                    <el-icon><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
                <div
                  v-if="isAuth('group:activity:delete')"
                  :class="[!(scope.row.status !== 1) ? 'disabled-btn' : '', 'default-btn text-btn']"
                  @click="onDelete(scope.row)"
                >
                  {{ $t('text.delBtn') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>
    <!-- 表格主体end -->

    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './add-or-update.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import $t from '@/utils/$t.js'
import http from '@/utils/http.js'
import { isAuth } from '@/utils/index'
import { ref, reactive, onMounted, nextTick } from 'vue'

let tempSearchForm = null // 保存上次点击查询的请求条件

const dataList = ref([])
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
// 头部搜索表单
const searchForm = reactive({
  activityName: '',
  status: '',
  prodName: ''
})

const addOrUpdateVisible = ref(false)
const activeName = ref('')
onMounted(() => {
  handleClick({ name: '0' })
})

const handleStatusChange = val => {
  activeName.value = val === '' ? '0' : (val > 0 ? val : val === 0 ? -1 : val) + ''
  getDataList()
}
const handleClick = tab => {
  const searchObj = JSON.parse(JSON.stringify(searchForm))
  searchObj.status = tab.name === '0' ? '' : tab.name === '-1' ? '0' : tab.name
  getDataList(null, searchObj)
}
const getDataList = (pageParam, argcSearchForm, newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(argcSearchForm || searchForm))
  }
  argcSearchForm && (tempSearchForm.status = argcSearchForm.status)
  http({
    url: http.adornUrl('/group/activity/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    const form = argcSearchForm || searchForm
    if (form?.status !== null) {
      searchForm.status = form.status === '' ? null : Number(form.status)
    }
    dataList.value = data.records
    page.total = data.total
  })
}
// 新增 / 修改
const addOrUpdateRef = ref(null)
const onAddOrUpdate = id => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}
const onDelete = row => {
  if (!(row.status !== 1)) {
    return
  }
  const ids = [row]
  ElMessageBox.confirm(
    $t('groups.confirmDelete') + row.activityName + $t('groups.active'),
    $t('text.tips'),
    {
      confirmButtonText: $t('crud.filter.submitBtn'),
      cancelButtonText: $t('crud.filter.cancelBtn'),
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl('/group/activity/' + row.groupActivityId),
      method: 'delete',
      data: http.adornData({})
    }).then(() => {
      page.total = page.total - ids.length
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  })
}
/**
 * 刷新回调
 */
const refreshChange = () => {
  getDataList(page)
}
// 点击搜索
const onSearch = (newData = false) => {
  page.currentPage = 1
  page.pageSize = 10
  if (searchForm.status !== null) {
    activeName.value =
      searchForm.status === '' ? '0' : searchForm.status === 0 ? '-1' : searchForm.status + ''
  }
  getDataList(page, null, newData)
}
const clearSearch = () => {
  searchForm.activityName = ''
  searchForm.status = ''
  searchForm.prodName = ''
}
// 失效活动活动
const invalidActivityHandle = row => {
  ElMessageBox.confirm(
    $t('groups.determinedToFail') + row.activityName + $t('groups.actTip'),
    $t('text.tips'),
    {
      confirmButtonText: $t('crud.filter.submitBtn'),
      cancelButtonText: $t('crud.filter.cancelBtn'),
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl('/group/activity/invalid/' + row.groupActivityId),
      method: 'PUT',
      data: http.adornData({})
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          getDataList(page)
        }
      })
    })
  })
}
// 启用拼团活动
const activeGroupActivity = groupActivityId => {
  http({
    url: http.adornUrl('/group/activity/active/' + groupActivityId),
    method: 'PUT',
    data: http.adornData({})
  }).then(() => {
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        getDataList(page)
      }
    })
  })
}
// 每页数量变更
const onPageSizeChange = val => {
  page.pageSize = val
  getDataList()
}
// 页数变更
const onPageChange = val => {
  page.currentPage = val
  getDataList()
}
</script>
